import { Breadcrumb, Button, Card, Col, Divider, Form, message, Modal, Popconfirm, Row, Space, Table, Tag, Tooltip, Input } from 'antd'
import { CaretRightOutlined, EditOutlined, DeleteOutlined, SettingOutlined } from '@ant-design/icons'
import React, { Component } from 'react'
import { addRole, deleteRightOfRole, getRoles, deleteRoleById, getRights, setRightsForRole, editRole } from '../../../api/right'
import './index.css'
export default class RoleList extends Component {
  state = {
    addRoleModalVisible:false,
    setRightModalVisiable: false,
    editRoleModalVisible:false,
    editRoleId:null,
    editRoleName:null,
    editRoleDesc:null,
    rightList: [],
    setRightId: null,
    defaultSelectedRowKeys:[],
    rightColumns: [
      {
        dataIndex: 'authName',
        key: 'authName',
        align: 'left'
      }
    ],
    selectionProps: {
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          defaultSelectedRowKeys:selectedRowKeys
        })
      },
      onSelect: (record, selected, selectedRows, nativeEvent) => {
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
      },
    },
    expandedRowKeys: [],
    roleList: [],
    RoleExpand: {
      // 如果不这样设置，会当做树形结构进行渲染
      childrenColumnName: 'nochildren',
      expandedRowRender: record => {
        const rights = record.children
        return (<div>{
          rights.map((item,index)=>{
            return (
              <Row className={index===0? 'role-auth-itemTop role-auth-item':'role-auth-item'} key={item.authName}>
                <Col span={5} className='role-auth-col'><Tag color="processing" closable onClose={_ => this.handleTagClose(record.id,item.id)}>{item.authName}</Tag><CaretRightOutlined /></Col>
                <Col span={19} className='role-auth-col'>
                  {
                    item.children.map(item1 => {
                      return (
                        <Row className='role-auth-item' key={item1.authName}>
                          <Col span={5} className='role-auth-col'><Tag color='success' closable onClose={_ => this.handleTagClose(record.id,item1.id)}>{item1.authName}</Tag><CaretRightOutlined /></Col>
                          <Col span={14} className='role-auth-col3'> 
                            {
                              item1.children.map(item2 => {
                                return <Tag color='warning' className='tag-item3' closable onClose={_ => this.handleTagClose(record.id,item2.id)} key={item2.authName}>{item2.authName}</Tag>
                              })
                            }
                          </Col>
                        </Row>
                      )
                    })
                  }
                </Col>
              </Row>
            )
          })
        }</div>)
      },
      rowExpandable: record => record.roleName && record.children && record.children.length > 0,
      onExpand: (expanded,record) => {
        const {expandedRowKeys} = this.state
        if(expanded){
          expandedRowKeys.push(record.id);
        }else{
          const index = expandedRowKeys.indexOf(record.id)
          expandedRowKeys.splice(index,1)
        }
        this.setState({
          expandedRowKeys
        })
      }
    },
    roleColumns:[
      {
        align: 'center',
        key: 'index',
        render: (text,record,index) => index + 1
      },
      {
        title:'角色名称',
        dataIndex: 'roleName',
        align: 'center',
        key: 'roleName'
      },
      {
        title:'角色描述',
        dataIndex: 'roleDesc',
        align: 'center',
        key: 'roleDesc'
      },
      {
        title:'操作',
        align: 'center',
        key: 'options',
        render: (text,record) => {
          return (
            <Space>
            <Tooltip title='编辑角色' placement='top'>
              <Button type='primary' icon={<EditOutlined/>} onClick={ _ => this.showEditRoleModal(record)} size='mini'></Button>
            </Tooltip>
            <Tooltip title='删除角色' placement='top'>
              <Popconfirm
                placement="bottomRight"
                title='确定要删除这个角色吗'
                onConfirm={_ => this.deleteRole(record.id)}
                okText="Yes"
                cancelText="No"
              >
                <Button type='danger' icon={<DeleteOutlined />} size='mini'></Button>
              </Popconfirm>
            </Tooltip>
            <Tooltip title='分配权限' placement='top'>
              <Button type='default' icon={<SettingOutlined onClick={_ => this.showSetRoleModal(record)} />} size='mini'></Button>
            </Tooltip>
          </Space>
          )
        }
      }
    ]
  }
  getRoleList = async () =>{
    const res = await getRoles();
    if(res.meta.status !== 200){
      message.error(res.meta.msg)
    }else{
      this.setState({
        roleList: res.data
      })
    }
  }
  getRightList = async ()=>{
    const res = await getRights('tree');
    if(res.meta.status !== 200){
      return message.error(res.meta.msg)
    }
    this.setState({
      rightList:res.data
    })
  }
  handleTagClose = async (roleId,rightId) => {
    const res = await deleteRightOfRole(roleId,rightId);
    if(res.meta.status === 200){
      message.success(res.meta.msg);
    }else{
      message.error(res.meta.msg)
    }
  }
  showEditRoleModal = async (record)=>{
    await this.setState({
      editRoleModalVisible:true,
      editRoleId:record.id,
      editRoleName:record.roleName,
      editRoleDesc:record.roleDesc,
    })
    this.refs.editRoleFormRef.setFieldsValue({
      ['roleName']:record.roleName,
      ['roleDesc']:record.roleDesc
    })
  }
  handleOKEditRole = ()=>{
    this.refs.editRoleFormRef.submit();
  }
  handleCancelEditRole = ()=>{
    this.refs.editRoleFormRef.resetFields();
    this.setState({
      editRoleModalVisible:false,
      editRoleId:null,
      editRoleName:null,
      editRoleDesc:null,
    })
  }
  onFinishEditRole = async (values)=>{
    const {roleName,roleDesc} = values
    const isChange = (roleName===this.state.editRoleName && roleDesc===this.state.roleDesc)
    if(!isChange){
      const res = await editRole(this.state.editRoleId,values)
      if(res.meta.status === 200){
        message.success("修改成功")
        this.getRoleList();
      }else{
        message.error(res.meta.msg)
      }
    }else{
      message.info('用户未作任何修改')
    }
    this.handleCancelEditRole()
  }
  onFinishEditRoleFailed = () =>{
    message.warning("请填写完整表单数据再提高！")
  }
  deleteRole = async  (id) => {
    const res  = await deleteRoleById(id);
    if(res.meta.status === 200){
      message.success(res.meta.msg)
      this.getRoleList()
    }else{
      message.error(res.meta.msg)
    }
  }
  addIdToSelected(item,arr){
    if(item.roleName){
      item.children.forEach(item1=>{
        this.addIdToSelected(item1,arr)
      })
    }else{
      arr.push(item.id);
      if(item.children && item.children.length){
        item.children.forEach(item2 => {
          this.addIdToSelected(item2, arr);
        })
      }
    }
  }
  showSetRoleModal = async (record)=>{
    let arr = []
    this.addIdToSelected(record,arr)
    await this.setState({
      setRightModalVisiable: true,
      defaultSelectedRowKeys: arr,
      setRightId: record.id
    })
  }
  handleOKSetRight = async ()=>{
    const res = await setRightsForRole(this.state.setRightId,this.state.defaultSelectedRowKeys.join(','));
    if(res.meta.status === 200){
      message.success(res.meta.msg)
      this.getRoleList()
    }else{
      message.error(res.meta.msg)
    }
    this.handleCancelSetRight()
  }
  handleCancelSetRight = async ()=>{
    await this.setState({
      setRightModalVisiable: false,
      setRightId:null,
      defaultSelectedRowKeys:[]
    })
  }
  showAddRoleModal = ()=>{
    this.setState({
      addRoleModalVisible:true,
    })
  }
  handleOKAddRole =  () => {
    this.refs.addRoleFormRef.submit();
  }
  handleCancelAddRole = () => {
    this.setState({
      addRoleModalVisible:false,
    })
    this.refs.addRoleFormRef.resetFields()
  }
  onFinishAddRole = async (values) => {
    const res = await addRole(values);
    if(res.meta.status === 201){
      message.success(res.meta.msg);
      this.getRoleList();
    }else{
      message.error(res.meta.msg);
    }
    this.handleCancelAddRole()
  }
  onFinishAddRoleFailed = () => {
    message.warn('请填写完整信息再提交！')
  }
  componentDidMount(){
    this.getRoleList();
    this.getRightList();
  }
  render() {
    return (
      <div>
        <Card>
          <Breadcrumb>
            <Breadcrumb.Item>首页</Breadcrumb.Item>
            <Breadcrumb.Item>权限管理</Breadcrumb.Item>
            <Breadcrumb.Item>角色列表</Breadcrumb.Item>
          </Breadcrumb>
          <Divider/>
          <Button type='primary' onClick={this.showAddRoleModal}>添加角色</Button>
          <Table 
            className='role-list-table'
            rowKey="id"
            bordered
            dataSource={this.state.roleList}
            columns={this.state.roleColumns}
            expandable={{
              ...this.state.RoleExpand,
              expandedRowKeys:this.state.expandedRowKeys
            }}>
          </Table>
        </Card>
        <Modal title='添加角色' 
          visible={this.state.addRoleModalVisible} 
          onOk={this.handleOKAddRole} 
          onCancel={this.handleCancelAddRole}
        >
          <Form 
            ref='addRoleFormRef'
            labelCol={{span:4}}
            labelAlign='right'
            onFinish={this.onFinishAddRole}
            onFinishFailed={this.onFinishAddRoleFailed}
          >
            <Form.Item
              label="角色名"
              name="roleName"
              rules={[{ required: true, message: '请输入角色名!' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="角色描述"
              name="roleDesc"
              rules={[{ required: true, message: '请输入角色描述!' }]}
            >
              <Input />
            </Form.Item>
          </Form>
        </Modal>
        <Modal title='分配权限' 
          visible={this.state.setRightModalVisiable}
          onOk={this.handleOKSetRight} 
          onCancel={this.handleCancelSetRight}
        >
          <Table
            ref='rightTreeRef'
            showHeader={false}
            rowKey='id'
            rowSelection = {{
              checkStrictly:true,
              selectedRowKeys:this.state.defaultSelectedRowKeys,
              type: 'checkbox',
              ...this.state.selectionProps
            }}
            pagination={{position:['none']}}
            columns={this.state.rightColumns}
            dataSource={this.state.rightList}
          />
        </Modal>
        <Modal title='编辑角色' 
          visible={this.state.editRoleModalVisible} 
          onOk={this.handleOKEditRole} 
          onCancel={this.handleCancelEditRole}
        >
          <Form 
            ref='editRoleFormRef'
            labelCol={{span:4}}
            labelAlign='right'
            onFinish={this.onFinishEditRole}
            onFinishFailed={this.onFinishEditRoleFailed}
          >
            <Form.Item
              label="角色名"
              name="roleName"
              rules={[{ required: true, message: '请输入角色名!' }]}
            >
              <Input value={this.state.editRoleName}/>
            </Form.Item>

            <Form.Item
              label="角色描述"
              name="roleDesc"
              rules={[{ required: true, message: '请输入角色描述!' }]}
            >
              <Input defaultValue={this.editRoleDesc}/>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }
}
